/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ru.staf.NetworkReportGenerator;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import java.io.InputStreamReader;
import java.io.LineNumberReader;

/**
 *
 * @author aezhov
 */
public class PanasonicFactory implements DeviceFactory {
    public Device getDeviceInfo(String mac, String ip) {
        String html = readURL("http://" + ip);
        int x = html.indexOf("networkcamera");
        if (x > 0) {
            System.out.println("Looks like network cam");
            int y = html.indexOf("<title>");
            String model = html.substring(y + 7, x);
            return new GenericPanasonicCam(model);
        }

        x = html.indexOf("wjnd");
        if (x > 0) {
            System.out.println("Looks like a recorder");
            String model = "WJ-ND400";
            return new GenericPanasonicRecorder(model);
        }

        // Checking if the device is a decoder
        html = readURL("http://" + ip + "/main.html");
        if (html != null) {
            return new GenericPanasonicDecoder("[UNKNOWN]");
        }
        
        return null;
    }

    public String readURL(String inurl)
    {
        System.out.println("=== Reading " + inurl);
        try {
            URL url = new URL(inurl);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            InputStream is = conn.getInputStream();
            LineNumberReader reader = new LineNumberReader(new InputStreamReader(is));

            String line = null;
            String doc = "";
            while ((line = reader.readLine()) != null) {
                doc += line;
            }

            String[] parts = doc.split("\\s+");
            doc = "";
            for (int i = 0; i < parts.length; i++) {
                doc += parts[i].toLowerCase();
            }

            return doc;

        } catch (java.net.MalformedURLException exc) {
            System.out.println("PanasonicFactory: URL exception " + exc);
        } catch (java.io.IOException exc) {
            System.out.println("PanasonicFactory: IO exception " + exc);
            exc.printStackTrace();
        } catch (Exception exc) {
            System.out.println("PanasonicFactory: Exception during html processing" + exc);
        }

        return null;
    }
}
